import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_smart_heating/common/event.dart';
import 'package:flutter_smart_heating/common/local_storage.dart';
import 'package:flutter_smart_heating/pages/article/article.dart';
import 'package:flutter_smart_heating/pages/complain/complain.dart';
import 'package:flutter_smart_heating/pages/home/home.dart';
import 'package:flutter_smart_heating/pages/information/information.dart';
import 'package:flutter_smart_heating/pages/user/user.dart';

import 'package:flutter_smart_heating/service/push_service.dart';
import 'package:flutter_smart_heating/ui/src/permission.dart';
import 'package:flutter_smart_heating/ui/ui.dart';
import 'package:get/get.dart';
import 'package:proste_indexed_stack/proste_indexed_stack.dart';

class NavItemDataModel {
  final String label;
  final IconData icon;
  final String name;
  final IconData iconActive;
  NavItemDataModel({
    required this.label,
    required this.icon,
    required this.iconActive,
    required this.name,
  });
}

class FragmentView extends StatefulWidget {
  const FragmentView({Key? key}) : super(key: key);

  @override
  State<FragmentView> createState() => _FragmentViewState();
}

class _FragmentViewState extends State<FragmentView>
    with WidgetsBindingObserver {
  int currentIndex = 0;
  final List<BottomNavigationBarItem> navbarItems = [];

  final List navBars = [
    {
      'label': '首页',
      'name': 'home',
      'icon': UiIcons.home,
      'iconActive': UiIcons.home_fill,
      'view': const HomePage(),
    },
    {
      'label': '资讯',
      'name': 'article',
      'icon': UiIcons.detail,
      'iconActive': UiIcons.detail_fill,
      'view': const ArticlePage(),
    },
    {
      'label': '大数据',
      'name': 'information',
      'icon': UiIcons.piechart,
      'iconActive': UiIcons.piechart_circle_fil,
      'view': const InformationPage(),
    },
    {
      'label': '投诉',
      'name': 'service',
      'icon': UiIcons.calendar,
      'iconActive': UiIcons.calendar_fill,
      'view': const ComplainPage(),
    },
    {
      'label': '我的',
      'name': 'user',
      'icon': UiIcons.user,
      'iconActive': UiIcons.user_fill,
      'view': const UserPage(),
    },
  ];

  final List<IndexedStackChild> pages = [];
  dynamic event;
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);

    for (var value in navBars) {
      NavItemDataModel item = NavItemDataModel(
          label: value['label'],
          icon: value['icon'],
          iconActive: value['iconActive'],
          name: value['name']);
      navbarItems.add(buildNavbarItem(item));
      pages.add(IndexedStackChild(child: value['view'] ?? Container()));
    }

    event =
        AppEvent().eventBus.on<RootSetCurrentTabIndexEvent>().listen((event) {
      List.generate(navBars.length, (index) {
        if ('/${navBars[index]['name']}' == event.uri.path) {
          if (event.uri.query != '') {
            Get.parameters = event.uri.queryParameters;
          }

          navbarItemClicked(index, query: event.uri.query);
        }
      });
    });
    Future.delayed(Duration.zero, initNotification);
  }

  initNotification() async {
    if (LocalStorage.instance.getItem('permission.notification') == 'yes') {
      return PushService.instance.init();
    }
    var permission =
        await UiPeromission.check(context, title: "消息通知需要打开以下权限", permissions: [
      UiPermissionData(
        '推送通知',
        Permission.notification,
        onlyAndroid: true,
      )
    ]);
    LocalStorage.instance.setItem('permission.notification', 'yes');
    if (permission) {
      PushService.instance.init();
    }
  }

  BottomNavigationBarItem buildNavbarItem(NavItemDataModel data) {
    return BottomNavigationBarItem(
      icon: Padding(
        padding: const EdgeInsets.only(bottom: 3.0),
        child: UiIcon(data.icon),
      ),
      activeIcon: Padding(
        padding: const EdgeInsets.only(bottom: 3.0),
        child: UiLinearGradientMask(
            child: UiIcon(
          data.iconActive,
          color: Colors.white,
        )),
      ),
      label: data.label,
    );
  }

  navbarItemClicked(int index, {String? query}) {
    int oldIndex = currentIndex;
    setState(() {
      currentIndex = index;
    });
    AppEvent().eventBus.fire(
          RootNavigateChangeEvent(
            index: index,
            name: navBars[index]['name'],
            reClicked: oldIndex == index,
            query: query,
          ),
        );
  }

  @override
  void dispose() {
    event.cancel();

    /// 移除观察者
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangePlatformBrightness() {
    super.didChangePlatformBrightness();
    //跟随系统更新主题颜色
    if (UiTheme.mode == ThemeMode.system) {
      Brightness current = MediaQuery.platformBrightnessOf(context);
      Get.changeThemeMode(
        current == Brightness.light ? ThemeMode.dark : ThemeMode.light,
      );
    }
  }

  int time = 0;
  @override
  Widget build(BuildContext context) {
    return PopScope(
      canPop: false,
      onPopInvoked: (back) {
        if (time == 1) {
          exit(0);
        }
        if (currentIndex > 0) {
          navbarItemClicked(currentIndex - 1);
        } else if (time == 0) {
          time = 1;
          Future.delayed(const Duration(seconds: 3), () {
            time = 0;
          });
          Ui.toast(
            '再按一次退出'.tr,
          );
        }
      },
      child: Scaffold(
        body: Column(
          children: [
            Expanded(
              child: ProsteIndexedStack(
                index: currentIndex,
                children: pages,
              ),
            ),
            const Divider(
              height: 0,
              thickness: 0.2,
            ),
          ],
        ),
        bottomNavigationBar: BottomNavigationBar(
          type: BottomNavigationBarType.fixed,
          elevation: 0,
          selectedFontSize: 11,
          unselectedFontSize: 11,
          currentIndex: currentIndex,
          items: navbarItems,
          onTap: navbarItemClicked,
        ),
      ),
    );
  }
}
